/**人员选择组件
 * @author xiaowei
 * @date 2017年6月2日
 */
Ext.define('App.ux.approval.MemberSelectWindow', {
    extend: 'Ext.window.Window',
    xtype: "approvalMemberSelectWindow",
    modal: true,
    width: 1100,
    height: 600,
    title: "请选择人员",
    alwaysOnTop: true,
	excludes: [],//排除人员，当查询人员时该组中的成员不会被显示
    layout: {
		type: 'hbox',
		align: 'stretch'
	},
    //buttonAlign: "center",
    initComponent: function() {
		//this.tbar = this._createTbar();
        this.items = this._createItems();
        this.buttons = this._createButtons();
        this.callParent();
    },
	
	listeners: {
        show: function(cmp, eOpts) {
            var selectedData = cmp.myTagField.getValueRecords();
            var myStore = cmp.down("grid[name='selectedMemberGrid']").store;
            myStore.removeAll();
            myStore.add(selectedData);
        }
    },
	
	_createTbar: function() {
        var win = this;
        return [{
            xtype: 'combo',
            name: 'conditionType',
			margin: '0 5 0 2',
            queryMode: 'local',
            displayField: 'value',
            valueField: 'key',
            value: "name",
            store: {
                fields: ['key', 'value'],
                data: [{
                    "key": "name",
                    "value": "姓名"
                }, {
                    "key": "personNo",
                    "value": "工号"
                }, {
                    "key": "orgName",
                    "value": "所属部门"
                }]
            }
        }, {
            xtype: 'textfield',
            name: 'conditionValue',
            enableKeyEvents: true,
            listeners: {
                keyup: function(cmp, e, eOpts) {
                    var btn = win.down("button[name='btnQueryRequest']");
                    if (e.getKey() == Ext.EventObject.ENTER) btn.fireEvent("click", btn);
                }
            }
        }, {
            xtype: 'button',
            name: 'btnQueryRequest',
            text: '查询',
            iconCls: 'fa fa-search fa-lg',
            listeners: {
                click: function(button) {
                    var conditionType = win.down("combo[name='conditionType']").value;
                    var conditionValue = win.down("textfield[name='conditionValue']").value.replace(/(^\s*)|(\s*$)/g, "");
                    var grid = win.down("grid[name='allMemberGrid']");
                    var store = grid.getStore();
                    var proxy = store.getProxy();

                    var params;
                    if (conditionType == 'name') {
                        params = {
                            personName: encodeURIComponent(conditionValue),
                            personNo: "",
                            orgName: "",
							orgCode: ""
                        };
                    } else if (conditionType == 'personNo') {
                        params = {
                            personName: "",
                            personNo: encodeURIComponent(conditionValue),
                            orgName: "",
                            orgCode: ""
                        };
                    } else {
                        params = {
                            personName: "",
                            personNo: "",
                            orgName: encodeURIComponent(conditionValue),
                            orgCode: ""
                        };
                    }
                    Ext.apply(store.proxy.extraParams, params);
                    store.loadPage(1);

                }
            }
        }];
    },
	
	_createItems: function() {
		
		return [
			this._createWest()
			,this._createCenter()
			,this._createEast()
		];
    },
	
	_createButtons: function() {
        var win = this;
        return [{
            xtype: 'button',
            name: 'btnQueryRequest',
            text: '确定',
            iconCls: 'fa fa-check fa-lg',
            listeners: {
                click: function(button) {
                    var myStore = win.down("grid[name='selectedMemberGrid']").store;

                    if (win.myTagField) {
                        win.myTagField.clearValue();

                        myStore.each(function(rec) {
                            win.myTagField.addValue(rec);
                        });

                        win.close();
                    }

                }
            }
        }, {
            xtype: 'button',
            name: 'cancel',
            text: '取消',
            iconCls: 'fa fa-times fa-1x',
            listeners: {
                click: function(button) {
                    win.close();
                }
            }
        }];
    },
	
    _createWest: function(){
		
		return {
			xtype: "fieldset",
			margin : '0 0 10 10',
			style: {
				background: '#fff'
			},
			padding: 0,
			title: "可选人员",
			width: 710,
			layout: 'fit',
			items: [
				{
					xtype: 'panel',
					layout: {
						type: 'hbox',
						align: 'stretch'
					},
					tbar: this._createTbar(),
					items: [
						{
							xtype: 'panel',
							width: 350,
							padding: '0 0 10 10',
							border: true,
							layout: 'fit',
							items: [
								this._createTree()
							]
						},
						this._createGrid()
					]
				}
				
			]

        };
	},
	
	_createCenter: function(){
		return {
			width: 40,
            layout: {
				type: 'vbox',
				align: 'stretch'
			},
            items: [
				{xtype: 'container',flex: 1},
				{
					xtype: "button",
					iconCls: "fa fa-forward",
					height: 30,
					handler: function(button) {
						var win = button.up("window");
						var leftGrid = win.down("grid[name='allMemberGrid']");
						var selRec = leftGrid.getSelection();
						if (selRec && selRec.length > 0) {
							var rightGrid = win.down("grid[name='selectedMemberGrid']");
							var rightGridStore = rightGrid.store;
							var rightRec;

							if (win.memberSelModel == "single") { //单选只能添加一个值,必选先删其他的
								rightGridStore.removeAll();
								rightGridStore.insert(0, selRec[0]);
							} else {
								Ext.Array.each(selRec, function(rec, index, countriesItSelf) {
									rightRec = rightGridStore.findRecord("id", rec.data.id);
									if (!rightRec) {
										rightRec = rightGridStore.insert(0, rec);
									}
								});
							}

							rightGrid.selModel.select(rightRec);
						}

					}
				},
				{xtype: 'container',height: 40},
				{
					xtype: "button",
					height: 30,
					iconCls: "fa fa-backward",
					handler: function(button) {
						var rightGrid = button.up("window").down("grid[name='selectedMemberGrid']");
						var selRec = rightGrid.getSelection();
						if (selRec && selRec.length > 0) {
							rightGrid.store.remove(selRec);
						}
					}
				},
				{xtype: 'container',flex: 1}
			]
        };
	},
	
	_createEast: function(){
		return {
			xtype: "fieldset",
			title: "已选人员",
			flex: 1,
			margin : '0 10 10 0',
			padding: '0 10 10 10',
			style: {
				background: '#fff'
			},
			layout: 'fit',
			items: [{
				xtype: "grid",
				columnLines: true,
				border: true,
				name: "selectedMemberGrid",
				listeners: {
					itemdblclick: function(view, record, item, index, e, eOpts) {
						var rightGrid = view.up("window").down("grid[name='selectedMemberGrid']");
						rightGrid.store.remove(record);
					}
				},
				selModel: {
					selType: 'checkboxmodel'
				},
				columns: [{
					xtype: 'rownumberer'
				}, {
					text: '工号',
					dataIndex: 'id',
					width: 60
				}, {
					text: '姓名',
					dataIndex: 'name',
					flex: 1
				}],
				store: Ext.create('Ext.data.Store', {
					fields: ["id", "name", "organizationId", "organizationName"]
				})

			}]
        };
	},
	
	_createMemberStore: function(){
		var excludes = this.excludes;
		return Ext.create('Ext.data.Store', {
            fields: [{
                name: 'id',
                type: 'string'
            }, {
                name: 'name',
                type: 'string'
            }, {
                name: 'loginName',
                type: 'string'
            }, {
                name: 'organizationId',
                type: 'string'
            }, {
                name: 'organizationName',
                type: 'string'
            }],
            pageSize: 10,
            autoLoad: true,
            autoSync: false,
            proxy: {
                type: 'ajax',
                 url: "activiti/user/getEmployee",
                reader: {
                    type: 'json',
                    rootProperty: 'data',
                    totalProperty: 'resultCount'
                },
                extraParams: {
                    personNo: '',
                    personName: '',
                    orgName: '',
                    orgCode: ''
                }
            },
			filters: [
				function(item) {
					if(!Ext.isEmpty(excludes)){
						for(var i=0; i<excludes.length; i++){
							if(item.data.loginName == excludes[i]){
								return false;
							}
						}
					}
					return true;
				}
			]
        });
	},
	_createTree: function(){
		var _this = this;
		return {
			xtype: "treepanel",
			displayField: 'orgName',
			useArrows: true,
			autoScroll: true,
			containerScroll: true,
            store: {
				fields: ['id', 'orgName'],
				root: {
					orgName: "组织机构",
					expanded: true,
					id: "50016195"
				},
				proxy: {
					type: 'ajax',
					url: "activiti/user/getOrgTree",
					reader: {
						rootProperty: 'children'
					}
				}

			},
			listeners: {
                afteritemexpand: function(node) {
                	if(node.id == '50016195') {
                        var currUser = App.CurrentUser;
                        if (currUser && currUser.organizationCode) {
                            var chiledNode2 = this.store.getNodeById(currUser.organizationCode);
                            if(chiledNode2) {
                                this.selectPath(chiledNode2.getPath());
                                var store = this.up("window").down("grid[name='allMemberGrid']").store;
                                Ext.apply(store.proxy.extraParams, {
                                    personName: "",
                                    personNo: "",
                                    orgName: "",
                                    orgCode: encodeURIComponent(chiledNode2.data.orgCode)
                                });
                                store.loadPage(1);
                            }
                        }
                    }
                },
				itemclick: function(cmp, record, item, index, e, eOpts) {
					var store = cmp.up("window").down("grid[name='allMemberGrid']").store;
					Ext.apply(store.proxy.extraParams, {
						personName: "",
						personNo: "",
						orgName: "",
                        orgCode: encodeURIComponent(record.data.orgCode)
					});
					store.loadPage(1);
				}
			}
		};
	},
	
	_createGrid: function(){
		var memberStore = this._createMemberStore();
		return {
			flex: 1,
			xtype: "grid",
			columnLines: true,
			border: true,
			padding: '0 10 10 10',
			name: "allMemberGrid",
			listeners: {
				itemdblclick: function(view, record, item, index, e, eOpts) {
					var win = view.up("window");
					var rightGrid = win.down("grid[name='selectedMemberGrid']");
					var rightGridStore = rightGrid.getStore();
					var rightRec = rightGridStore.findRecord("id", record.data.id);
					if (!rightRec) {
						if (win.memberSelModel == "single") { //单选只能添加一个值,必选先删其他的
							rightGridStore.removeAll();
						}
						rightRec = rightGridStore.insert(0, record);
					}
					rightGrid.selModel.select(rightRec);
				}
			},
			selModel: {
				selType: 'checkboxmodel'
			},
			store: memberStore,
			columns: [{
				xtype: 'rownumberer'
			}, {
				text: '工号',
				dataIndex: 'id',
				width: 60
			}, {
				text: '姓名',
				dataIndex: 'name',
				width: 100,
				flex: 1
			}],

			dockedItems: [{
				xtype: 'pagingtoolbar',
				dock: 'bottom',
				prependButtons: true,
				//displayInfo: true,
				store: memberStore
			}]
		};
	}
});